package com.uyun.rbac.shiro;

import com.uyun.app.main.service.MainService;
import com.uyun.rbac.permission.entity.GroupEntity;
import com.uyun.rbac.permission.entity.PermissionEntity;
import com.uyun.rbac.permission.entity.RoleEntity;
import com.uyun.rbac.permission.entity.UserEntity;
import com.uyun.rbac.user.service.UserService;
import com.uyun.util.AppUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;


public class MyRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Resource
    MainService mainService;
    @Resource
    UserService userService;


    /**
     * 为当前登录的Subject授予角色和权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
        String currentUsername = (String) super.getAvailablePrincipal(principals);

        UserEntity userEntity = userService.getUserEntityByUserName(currentUsername);
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();

        if(userEntity!=null){

            GroupEntity groupEntity = userEntity.getGroupEntity();
            List<RoleEntity> roleEntityList = groupEntity.getRoleEntityList();
            for(RoleEntity roleEntity:roleEntityList){
                List<PermissionEntity> permissionEntityList = roleEntity.getPermissionEntityList();
                permissionEntityList.stream().forEach(permissionEntity ->
                        simpleAuthorInfo.addStringPermission(permissionEntity.getMapping()));
                simpleAuthorInfo.addRole(roleEntity.getRoleName());
            }
        }

        return simpleAuthorInfo;
    }

    /**
     * 验证当前登录的Subject
     * 经测试:本例中该方法的调用时机为执行Subject.login()时
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)  {
        // 获取基于用户名和密码的令牌
        // 实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的
        // 两个token的引用都是一样的
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String val_pwd = mainService.getPwdByUserName(token.getUsername());

        if(AppUtils.StringUtil(val_pwd)==null){
            throw new UnknownAccountException();//没找到帐号
        }

        String username = token.getUsername();
        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(username, val_pwd, this.getName());
        this.setSession("currentUser", username);

        return authcInfo;
        // 此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息
        // 说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的,本例中为了演示就硬编码了)
        // 这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证
        // 没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常

    }

    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     *
     * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }



}
